// releasePage/pages/AddFood/AddFood.js
import throttle from '../../../utils/throttle.js';
import Http from '../../../utils/http.js';
const http = new Http();
const app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        review: '', //审核编辑标记位
        ipxBottom: 0,
        type: '', //00--经验转   01--城市公告转    01--车食住行再次编辑
        id: '',
        contentInfo: {}, //再次编辑内容
        sceneImageArr: [], //上传照片
        descriptionlength: 0,
        description: '',
        titleNameValue: '',
        addressValue: '',
        lng: '',
        lat: '',
        citylng: '',
        citylat: '',
        city: '',
        country: '',
        classValue: '',
        netSpeedValue: '', //网络速度
        netSpeedIndex: '', //网络状况
        classIndex: '', //02车 03美食 04住宿 05出行
        actions: [
            {
                name: '租车',
                color: '#333333',
            },
            {
                name: '住宿',
                color: '#333333',
            },
            {
                name: '出行',
                color: '#333333',
            },
            {
                name: '美食/三餐',
                color: '#333333',
            },
        ],
    },
    cityTap() {
        wx.navigateTo({
            url: `../chooseCity/chooseCity`,
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options.cszx);
        if (app.globalData.isIpx) {
            this.setData({
                ipxBottom: 34,
            });
        }

        if (options.type) {
            //02车 03美食 04住宿 05出行
            if (options.cszx == '01') {
                this.setData({
                    classIndex: '02',
                    classValue: '租车',
                });
            } else if (options.cszx == '02') {
                this.setData({
                    classIndex: '03',
                    classValue: '美食/三餐',
                });
            } else if (options.cszx == '03') {
                this.setData({
                    classIndex: '04',
                    classValue: '住宿',
                });
            } else if (options.cszx == '04') {
                this.setData({
                    classIndex: '05',
                    classValue: '出行',
                });
            }
            this.setData({
                id: options.id,
                type: options.type,
                review: options.review || '',
            });
            this.geteditInfo(options.type, options.id);
        } else {
            wx.setNavigationBarTitle({
                title: '添加车食住行·' + app.globalData.addressBack,
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    titleInput: function (e) {
        this.setData({
            titleNameValue: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 30);
    },
    description(e) {
        this.setData({
            description: e.detail.value,
            descriptionlength: e.detail.value.length,
        });
        app.numLimitTip(e.detail.value.length, 500);
    },
    //显示弹出层
    classTap() {
        // 关闭键盘
        wx.hideKeyboard({
            complete: (res) => {
                console.log('hideKeyboard res', res);
            },
        });
        if (this.data.type == '02') return;
        this.setData({
            show: true,
        });
    },
    //取消
    onCancel() {
        this.setData({
            show: false,
        });
    },
    // 网速选择弹窗
    netSpeedBtn(e) {
        // 关闭键盘
        wx.hideKeyboard({
            complete: (res) => {
                console.log('hideKeyboard res', res);
            },
        });
        this.setData({
            netSpeedShow: true,
        });
    },
    onClose() {
        this.setData({
            netSpeedShow: false,
        });
    },
    // 选择网速状况
    choiceNetSpeed(e) {
        this.setData({
            netSpeedIndex: e.currentTarget.dataset.index,
            netSpeedValue: e.currentTarget.dataset.value,
        });
        this.onClose();
    },
    onDelect(e) {
        let _that = this;
        //02车 03美食 04住宿 05出行
        if (e.detail.name == '租车') {
            this.setData({
                classValue: e.detail.name,
                classIndex: '02',
                show: false,
            });
        } else if (e.detail.name == '住宿') {
            this.setData({
                classValue: e.detail.name,
                classIndex: '04',
                show: false,
            });
        } else if (e.detail.name == '出行') {
            this.setData({
                classValue: e.detail.name,
                classIndex: '05',
                show: false,
            });
        } else if (e.detail.name == '美食/三餐') {
            this.setData({
                classValue: e.detail.name,
                classIndex: '03',
                show: false,
            });
        }
    },
    // GPS选择
    openLocation: function () {
        var _that = this;
        wx.chooseLocation({
            latitude:
                _that.data.lat || _that.data.citylat || app.globalData.cityLat,
            longitude:
                _that.data.lng || _that.data.citylng || app.globalData.cityLng,
            success: function (res) {
                _that.setData({
                    addressValue: res.address || res.name,
                    lng: res.longitude,
                    lat: res.latitude,
                    gps:
                        res.longitude.toFixed(1) +
                        '°E，' +
                        res.latitude.toFixed(1) +
                        '°N',
                });
            },
            fail: function (res) {
                console.log(res);
            },
        });
    },
    // 添加图片
    addImg() {
        const that = this;
        wx.chooseImage({
            count: 8 - that.data.sceneImageArr.length,
            success(res) {
                let imgLen =
                    that.data.sceneImageArr.length + res.tempFilePaths.length;
                if (imgLen > 8) {
                    wx.showModal({
                        content: '最多上传8张图片，请重新上传',
                        showCancel: false,
                    });
                    return;
                } else {
                    wx.showLoading({
                        title: '图片上传中',
                        mask: true,
                    });
                    const imgUploadResults = [];
                    let index = that.data.sceneImageArr.length;
                    for (let i = 0; i < res.tempFilePaths.length; i++) {
                        let imgUploadResult = app
                            .imgUpload(res.tempFilePaths[i])
                            .then((res) => {
                                let num = i + index;
                                that.data.sceneImageArr[num] = res;
                                that.setData({
                                    sceneImageArr: that.data.sceneImageArr,
                                });
                                console.log(that.data.sceneImageArr);
                            });
                        imgUploadResults.push(imgUploadResult);
                    }
                    Promise.all(imgUploadResults).then((values) => {
                        wx.hideLoading();
                    });
                }
            },
        });
    },
    // 删除图片
    deleteImg(e) {
        let index = e.currentTarget.dataset.index;
        console.log(index);
        this.data.sceneImageArr.splice(index, 1);
        this.setData({
            sceneImageArr: this.data.sceneImageArr,
        });
    },
    // 预览图片
    previewImage(e) {
        const current = e.target.dataset.src;
        wx.previewImage({
            current,
            urls: this.data.sceneImageArr,
        });
    },
    geteditInfo(type, id) {
        let _that = this;
        if (type == '00') {
            //经验跳转
            http.getRequest(
                `cjMap/getExperienceDetail?authId=${app.globalData.authId}&id=${id}`
            ).then((res) => {
                if (res.status == 0) {
                    console.log(res);
                    _that.setData({
                        contentInfo: res.experience,
                        description: res.experience.content,
                        titleNameValue: res.experience.title,
                        addressValue: res.experience.address,
                        lng: res.experience.lng,
                        lat: res.experience.lat,
                        citylng: res.experience.citylng,
                        citylat: res.experience.citylat,
                        city: res.experience.city,
                        country: res.experience.country,
                        sceneImageArr: res.experience.picurl
                            ? JSON.parse(res.experience.picurl)
                            : [],
                    });
                }
            });
        } else if (type == '01') {
            //公告跳转
            http.getRequest(
                `cjMap/getCityNoticeDetail?authId=${app.globalData.authId}&id=${id}`
            ).then((res) => {
                if (res.status == 0) {
                    console.log(res);
                    _that.setData({
                        contentInfo: res.experience,
                        description: res.experience.content,
                        titleNameValue: res.experience.title,
                        addressValue: res.experience.address,
                        lng: res.experience.lng,
                        lat: res.experience.lat,
                        citylng: res.experience.citylng,
                        citylat: res.experience.citylat,
                        city: res.experience.city,
                        country: res.experience.country,
                        sceneImageArr: res.experience.picurl
                            ? JSON.parse(res.experience.picurl)
                            : [],
                    });
                }
            });
        } else if (type == '02') {
            //车食住行再次编辑classIndex: '',        //02车 03美食 04住宿 05出行
            let httpName;
            if (_that.data.classIndex == '02') {
                httpName = 'getTransportationDetails';
            } else if (_that.data.classIndex == '03') {
                httpName = 'getFoodDetails';
            } else if (_that.data.classIndex == '04') {
                httpName = 'getAccommodationDetails';
            } else if (_that.data.classIndex == '05') {
                httpName = 'getTripDetails';
            }
            http.getRequest(
                `cjMap/${httpName}?authId=${app.globalData.authId}&id=${id}`
            ).then((res) => {
                if (res.status == 0) {
                    console.log(res.data);
                    _that.setData({
                        contentInfo: res.data,
                        description: res.data.excontent,
                        titleNameValue: res.data.title,
                        addressValue: res.data.address,
                        lng: res.data.lng,
                        lat: res.data.lat,
                        city: res.data.city,
                        country: res.data.country,
                        sceneImageArr: res.data.picurl
                            ? JSON.parse(res.data.picurl)
                            : [],
                        netSpeedIndex: res.data.networkspeed || '00', //车食住行网速图标
                        netSpeedValue:
                            res.data.networkspeed == '04'
                                ? '网速超快'
                                : res.data.networkspeed == '03'
                                ? '网速快'
                                : res.data.networkspeed == '02'
                                ? '网速ok'
                                : res.data.networkspeed == '01'
                                ? '网速差'
                                : '',
                    });
                    wx.setNavigationBarTitle({
                        title: '车食住行·' + res.data.city,
                    });
                }
            });
        }
        if (type != '02') {
            wx.setNavigationBarTitle({
                title: '移至城市车食住行',
            });
        }
    },
    submit: throttle(
        function (e) {
            let _that = this;
            if (app.visitorPublish()) return; //游客发布限制
            if (
                _that.data.description.length === 0 ||
                !_that.data.classIndex ||
                !_that.data.titleNameValue
            )
                return;
            if (_that.data.type == '00' || _that.data.type == '01') {
                if (!_that.data.city || !_that.data.country) return;
            }
            // wx.showModal({
            //     title: '确认提交？',
            //     content: '',
            //     success: function (res) {
            //         if (res.confirm) {

            //         } else {
            //             console.log('点击取消回调');
            //         }
            //     },
            // });
            // let _that.data.classIndex;
            //02车 03美食 04住宿 05出行
            let data = _that.data.contentInfo;
            data.delflg = '02'; //删除标志 00未删除 01已删除 02待审核 10草稿
            data.picurl = JSON.stringify(_that.data.sceneImageArr);
            data.excontent = _that.data.description;
            data.city = _that.data.city || app.globalData.addressBack; //城市
            data.country = _that.data.country || app.globalData.countryBack; //国家
            data.effectiveflg = '00';
            data.lng = _that.data.lng;
            data.lat = _that.data.lat;
            data.address = _that.data.addressValue; //地址
            data.title = _that.data.titleNameValue;
            data.networkspeed = _that.data.netSpeedIndex || '00';
            data.curlat = app.globalData.locationLat;
            data.curlng = app.globalData.locationLng;
            //00--经验转   01--城市公告转    01--车食住行再次编辑
            if (_that.data.type == '00') {
                //经验跳转
                http.postRequest(
                    `cjMap/changeExperienceToOther?authId=${app.globalData.authId}&type=${_that.data.classIndex}&experienceid=${_that.data.id}`,
                    data
                ).then((res) => {
                    if (res.status == 0) {
                        wx.removeStorageSync('refreshMapPointId'); //刷新地图标记点
                        app.globalData.expRefresh = true;
                        app.globalData.indexExpRefresh = true;
                        _that.setData({
                            classIndex: '',
                        });
                        wx.showToast({
                            title: '提交成功',
                            icon: 'success',
                            duration: 2000,
                        });
                        let pages = getCurrentPages(); //当前页面栈
                        let prevPage = pages[pages.length - 2]; //上一页面
                        if (
                            typeof prevPage.handleChangeExperience == 'function'
                        ) {
                            prevPage.handleChangeExperience();
                        } else {
                            prevPage.refresh();
                        }
                    }
                });
            } else if (_that.data.type == '01') {
                wx.request({
                    url:
                        app.globalData.rootPath +
                        `cjMap/changeCityNoticeToOther?authId=${app.globalData.authId}&type=${_that.data.classIndex}&noticeid=${_that.data.id}`,
                    method: 'POST',
                    header: {
                        'content-type': 'application/json',
                    },
                    data: data,
                    success: function (res) {
                        console.log(res);
                        if (res.data.status == 0) {
                            wx.removeStorageSync('refreshMapPointId');
                            _that.setData({
                                classIndex: '',
                            });
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 2000,
                            });
                            let pages = getCurrentPages(); //当前页面栈
                            let prevPage = pages[pages.length - 2]; //上一页面
                            prevPage.refresh();
                        } else {
                            wx.showToast({
                                title: '提交失败，请重新录入或联系后台管理',
                                icon: 'none',
                                duration: 2000,
                            });
                        }
                    },
                });
            } else if (_that.data.type == '02') {
                //编辑车食住行
                let httpName;
                let reviewType;
                if (_that.data.classIndex == '02') {
                    httpName = 'editTransportation';
                    reviewType = 11;
                } else if (_that.data.classIndex == '03') {
                    httpName = 'editDeliciousFood';
                    reviewType = 14;
                } else if (_that.data.classIndex == '04') {
                    httpName = 'editAccommodation';
                    reviewType = 12;
                } else if (_that.data.classIndex == '05') {
                    httpName = 'editTrip';
                    reviewType = 13;
                }
                http.postRequest(
                    `cjMap/${httpName}?authId=${app.globalData.authId}&id=${_that.data.id}&type=${_that.data.classIndex}`,
                    data
                ).then((res) => {
                    if (res.status == 0) {
                        if (!_that.data.review) {
                            app.globalData.indexExpRefresh = true;
                            wx.removeStorageSync('refreshMapPointId');
                            _that.setData({
                                classIndex: '',
                            });
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                duration: 2000,
                            });
                            let pages = getCurrentPages(); //当前页面栈id
                            let prevPage = pages[pages.length - 2]; //上一页面
                            prevPage.refresh(['cszx', 'count']);
                        } else {
                            app.doVerify(res.data.id, reviewType);
                        }
                    }
                });
            } else {
                //发布车食住行
                let httpName;
                if (_that.data.classIndex == '02') {
                    httpName = 'createTransportation';
                } else if (_that.data.classIndex == '03') {
                    httpName = 'createDeliciousFood';
                } else if (_that.data.classIndex == '04') {
                    httpName = 'createAccommodation';
                } else if (_that.data.classIndex == '05') {
                    httpName = 'createTrip';
                }
                http.postRequest(
                    `cjMap/${httpName}?authId=${app.globalData.authId}`,
                    data
                ).then((res) => {
                    if (res.status == 0) {
                        _that.setData({
                            classIndex: '',
                        });
                        wx.showToast({
                            title: '提交成功',
                            icon: 'success',
                            duration: 2000,
                        });
                        let pages = getCurrentPages(); //当前页面栈id
                        let prevPage = pages[pages.length - 2]; //上一页面
                        prevPage.refresh(['cszx', 'count']);
                    }
                });
            }
            if (!_that.data.review) {
                setTimeout(function () {
                    wx.navigateBack({
                        delta: 1, // 返回上一级页面。
                    });
                }, 2000);
            }
        },
        4000,
        {
            trailing: false,
        }
    ),
});
